package com.gdc.miaosha.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.gdc.miaosha.constants.RedisConstant;
import com.gdc.miaosha.entity.User;
import com.gdc.miaosha.request.LoginUserRequest;
import com.gdc.miaosha.result.CodeMsg;
import com.gdc.miaosha.result.Result;
import com.gdc.miaosha.service.IUserService;
import com.gdc.miaosha.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

import static com.gdc.miaosha.constants.CommonConstant.COOKIE_KEY;
import static com.gdc.miaosha.constants.RedisConstant.EXPIRED_2_DAY;

/**
 * Description: 登陆接口
 * @author: gdc
 * @date: 2022/4/4
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private IUserService userService;

    @GetMapping("/to_login")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/do_login")
    @ResponseBody
    public Result<Boolean> doLogin(HttpServletResponse response, @Validated LoginUserRequest request) {
        log.info("登陆请求信息为：{}", request.toString());

        User user = userService.getByMobile(request.getMobile());
        if (Objects.isNull(user)) {
            return Result.error(CodeMsg.MOBILE_NOT_EXIST);
        }

        // 密码校验
        String md5Pwd = SecureUtil.md5(request.getPassword() + user.getSalt());
        if (!Objects.equals(md5Pwd, user.getPassword())) {
            return Result.error(CodeMsg.MOBILE_NOT_EXIST);
        }

        // 将用户信息以 token 形式，写入到Redis
        String token = IdUtil.simpleUUID();
        RedisUtil.set(RedisConstant.TOKEN_PREFIX + token, JSON.toJSONString(user), EXPIRED_2_DAY);

        // 浏览器将 token key，返回给浏览器
        Cookie cookie = new Cookie(COOKIE_KEY, token);
        cookie.setMaxAge(EXPIRED_2_DAY);
        cookie.setPath("/");
        response.addCookie(cookie);

        return Result.success(true);
    }
}
